package de.karlNet.login;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import de.karlNet.sambamanager.ldapController.LdapMemberOfTree;
import de.karlNet.sambamanager.ldapModel.LdapObject;

@Controller
@RequestMapping("login")
public class LoginService {
	@Autowired
	private LoginCommand loginCommand;
	@Autowired
	private LdapUsernameLookup ldapUsernameLookup;

	@Autowired
	private LoginBean loginBean;

	@Autowired
	private LdapMemberOfTree ldapMemberOfTree;

	public @ResponseBody
	String sayHello(@PathVariable String to) {
		System.out.println("helo " + to);
		return "helo to";
	}

	@RequestMapping("is_in_group/{username}/{group}")
	public @ResponseBody String checkGroup(@PathVariable String username, @PathVariable String group) {
		this.loginBean.setLoggedIn(true);
		String dn = this.ldapUsernameLookup.lookupDN(username);
		String dnOfGroup = this.ldapUsernameLookup.lookupDN(group);
		List<LdapObject> memberIn = this.ldapMemberOfTree
				.getAllChildrenOfDN(dn);
		String inGroup = "false";
		for (LdapObject member : memberIn) {
			if (member.getDn().equals(dnOfGroup)) {
				inGroup = "true";
				break;
			}
		}
		this.loginCommand.reset();
		this.loginBean.setLoggedIn(false);
		return inGroup;
	}

	@RequestMapping("login_withgroup/{username}/{password}/{group}")
	public @ResponseBody
	String loginWithGroup(@PathVariable String username,
			@PathVariable String password, @PathVariable String group) {
		String dn = this.ldapUsernameLookup.lookupDN(username);
		boolean loginResult = this.loginCommand.login(dn, password);
		if (!loginResult) {
			return "" + false;
		}
		this.loginBean.setLoggedIn(loginResult);
		boolean inGroup = this.checkGroup(username, group).equals("true")?true:false;
		
		System.out.println(loginResult & inGroup);
		return "" + (loginResult & inGroup);
	}
}
